package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.CollectAdapter;
import com.sxm.yiwei.beans.Collect;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class MsgFollowActivity extends BaseActivity implements View.OnClickListener{
    private String TAG ="Follow";
    private ImageView follectback;
    private SlideListView1 collectlist;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private int no = 1;
    private String longitude;
    private String latitude;
    private CollectAdapter adapter;
    private ImageView nodata;
    private ImageView backmain;
    private View mFooterView;
    List<Collect.DataBean> list = new ArrayList<Collect.DataBean>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg_follow);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        longitude = sharedPreferences.getString("longitude", "");
        latitude = sharedPreferences.getString("latitude", "");
        initFollectView();


        getCollectList(no);

        adapter = new CollectAdapter(MsgFollowActivity.this,list);
        collectlist.setAdapter(adapter);
        collectlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Collect.DataBean dataBean = adapter.list.get(position);
                String id1 = dataBean.getId();
                Intent intent = new Intent(MsgFollowActivity.this,FWShopActivity.class);
                intent.putExtra("id",id1);
                startActivity(intent);
            }
        });
        adapter.setOnClickDelete(new CollectAdapter.OnClickDelete() {
            @Override
            public void OnDelete(int p) {
                Collect.DataBean dataBean = adapter.list.get(p);

                concernShop(dataBean.getId(),p);
            }


        });

        collectlist.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                if (firstVisibleItem == 0) {
                    View firstVisibleItemView = collectlist.getChildAt(0);
                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
                        no++;
                        getCollectList(no);
                    }
                } else if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    View lastVisibleItemView = collectlist.getChildAt(collectlist.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == collectlist.getHeight()) {
                        no++;
                        getCollectList(no);
                    }
                }
            }
        });
    }

    private void getCollectList(int no) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.COLLECTLIST);
        params.addHeader("Content-Type","application/json");
        params.addHeader("appId", appId);
        params.addHeader("token", token);
        params.addHeader("userId", userId);
        JSONObject obj = new JSONObject();
        obj.put("pageNo",no+"");
        obj.put("pageSize","20");
        obj.put("longitude",longitude);
        obj.put("latitude",latitude);
        params.addParameter("params",obj.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    getUtilData(result);
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ErrType.errType(MsgFollowActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getUtilData(String result) {
        JSONObject object = JSON.parseObject(result);
        JSONArray data = object.getJSONArray("data");

        if (data.size()==0){

        }else {
            nodata.setVisibility(View.GONE);
        }
        for (int i = 0; i < data.size(); i++) {
            Collect.DataBean dataBean = new Collect.DataBean();
            JSONObject obj1 = JSON.parseObject(String.valueOf(data.get(i)));
            String avatar = obj1.getString("avatar");
            String distance = obj1.getString("distance");
            String gradeCode = obj1.getString("gradeCode");
            String id = obj1.getString("id");
            String intro = obj1.getString("intro");
            String isInsurance = obj1.getString("isInsurance");
            String name = obj1.getString("name");
            String sellGrade = obj1.getString("sellGrade");
            String type = obj1.getString("type");
            dataBean.setAvatar(avatar);
            dataBean.setId(id);
            dataBean.setDistance(Double.valueOf(distance));
            dataBean.setGradeCode(Integer.valueOf(gradeCode));
            dataBean.setIntro(intro);
            dataBean.setName(name);
            dataBean.setSellGrade(Integer.valueOf(sellGrade));
            dataBean.setType(Integer.valueOf(type));
            if (isInsurance.equals("true")){
                dataBean.setIsInsurance(true);
            }else {
                dataBean.setIsInsurance(false);
            }
            list.add(dataBean);
        }

    }

    // 关注店铺
    public void concernShop(String id, final int p) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.SHOPCONCERN);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);

        JSONObject object = new JSONObject();
        object.put("shopId",id);

        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Toast.makeText(MsgFollowActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                adapter.list.remove(p);
                adapter.notifyDataSetChanged();
                try {
                    collectlist.turnToNormal();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                collectlist.invalidate();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(MsgFollowActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void initFollectView() {
        follectback = (ImageView) findViewById(R.id.message_followback);
        collectlist = (SlideListView1) findViewById(R.id.collect_list);
        backmain = (ImageView) findViewById(R.id.msgfollow_backmain);
        backmain.setOnClickListener(this);
        nodata = (ImageView) findViewById(R.id.msgfollow_nodata);
        follectback.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.message_followback:

                finish();
                break;
            case R.id.msgfollow_backmain:

                startActivity(new Intent(MsgFollowActivity.this,MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
        }
    }
}
